<?php
/**
 * Created by PhpStorm.
 * User: kkw
 * Date: 2019/1/27
 * Time: 19:48
 */

namespace kkw\goods\response;

use kkw\goods\table\GoodsImgTable;
use kkw\user\Util;
use suda\core\Request;
use suda\core\Response;

class UploadResponse extends Response
{

    public function onRequest(Request $request)
    {

        Util::printHeader();

        // 上传图片
        if (Request::isPost()) {
            if ($user_id = Util::getUserId()) {

                // 实例化的数据表
                $goods_img = new GoodsImgTable();
                // 上传文件开始
                $file = Request::files('file');
                $ext = pathinfo($file['name'], PATHINFO_EXTENSION);
                $saveName = substr(md5($file['tmp_name']), 0, 10) . '.' . $ext;
                $path = APP_PUBLIC . '/upload/';
                if (!is_dir($path)) {
                    mkdir($path);
                }
                move_uploaded_file($file['tmp_name'], $path . '/' . $saveName);
                // 上传文件结束
                try {
                    $goods_img->insert([
                        'path' => $saveName,
                        'user_id' => $user_id,
                        'goods_id' => 0
                    ]);
                } catch (\suda\exception\SQLException $e) {
                    $this->json(['code' => $e->getCode(), 'message' => '上传图片失败']);
                    return;
                }
                $this->json(['code' => 0, 'message' => '上传图片成功']);
            } else {
                $this->json(['code' => 1, 'message' => '上传图片出错']);
            }
        }
    }
}